package com.chengweiyi.security.security;

import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author xiao hu die
 * @Date 2022/5/11 19:05
 * @Version 1.0
 */
@Component
public class TokenManager {
/**Token有效时长*/
private long tokenEcpiration =24*60*60*1000;
/**编码秘钥*/
private String tokenSingKey ="123456";
/**生成TOKEN*/
public  String createToken(String userName){
    String compact = Jwts.builder().setSubject(userName).setExpiration(new Date(tokenEcpiration)).
            signWith(SignatureAlgorithm.HS512, tokenSingKey).compressWith(CompressionCodecs.GZIP)
            .compact();
    return compact;
}
   /**根据token得到用户信息*/
   public Claims getUserInfoFromToken(String token ){
       Claims claims;
       try {
           claims = Jwts.parser().setSigningKey(tokenSingKey).parseClaimsJws(token).getBody();
       }catch (ExpiredJwtException e){
            claims = e.getClaims();
       }
       return claims;
   }

   /* public static void main(String[] args) {
        TokenManager tokenManager = new TokenManager();
        String c = tokenManager.createToken("陈唯怡");
        System.out.println(c);
        Claims userInfoFromToken = tokenManager.getUserInfoFromToken(c);
        System.out.println(userInfoFromToken.getSubject().toString());
    }*/
}
